from flask import flash, redirect, url_for, render_template
from flask_login import login_required, current_user
from app import db
from app.libs.enums import PendingStatus
from app.models.drift import Drift
from app.models.gift import Gift
from app.setting import FIVE
from app.view_models.gift import GiftViewModel
from . import web


@web.route('/my/gifts')
@login_required
def my_gifts():
    uid = current_user.id
    gifts = Gift.get_user_gifts(uid)
    isbn_list = [gift.isbn for gift in gifts]
    # 拿到想要用户数量和对应的isbn号
    wish_list = Gift.get_wish_counts(isbn_list)
    view_model = GiftViewModel(gifts, wish_list)
    return render_template('my_gifts.html', gifts=view_model.gifts)


@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    if current_user.can_save_to_list(isbn): # 因为验证逻辑比较复杂,可以写在模型类中.
        with db.auto_commit():
            gift = Gift()
            gift.isbn = isbn
            gift.uid = current_user.id
            current_user.beans += FIVE # 当前用户的虚拟货币+5
            db.session.add(gift)

    else:
        flash('书籍存在心愿清单,或已赠送,请不要重复添加.')
    return redirect(url_for('web.book_detail', isbn=isbn))


@web.route('/gifts/<gid>/redraw')
def redraw_from_gifts(gid):
    # 撤销当前用户所赠送的礼物
    gift = Gift.query.filter_by(id=gid, uid=current_user.id, launched=False).first_or_404()
    # 查询当前赠送清单中的礼物有没有被赠送,如果被赠送先去鱼漂中处理,再到赠送清单中处理
    drift = Drift.query.filter_by(gift_id=gid, pending=PendingStatus.Waiting.value).first()
    if drift:
        flash('请先去往鱼漂处理书籍')
    else:
        with db.auto_commit():
            current_user.beans -= 1
            gift.delete()
    return redirect(url_for('web.my_gifts'))